package com.gitee.wsl.jvm.okhttp.base

import okhttp3.Headers
import okio.Source
import okio.buffer
import okio.gzip
import okio.source
import org.brotli.dec.BrotliInputStream
import java.util.Locale


val Headers.containsGzip: Boolean
    get() {
        return this["Content-Encoding"].equals("gzip", ignoreCase = true)
    }

val Headers.containsBrotli: Boolean
    get() {
        return this["Content-Encoding"].equals("br", ignoreCase = true)
    }

private val supportedEncodings = listOf("identity", "gzip", "br")

val Headers.hasSupportedContentEncoding: Boolean
    get() = get("Content-Encoding")
        ?.takeIf { it.isNotEmpty() }
        ?.let { it.lowercase(Locale.ROOT) in supportedEncodings }
        ?: true



fun Headers.redact(names: Iterable<String>): Headers {
    val builder = newBuilder()
    for (name in names()) {
        if (names.any { userHeader -> userHeader.equals(name, ignoreCase = true) }) {
            builder[name] = "**"
        }
    }
    return builder.build()
}

fun Source.uncompress(headers: Headers) = when {
    headers.containsGzip -> gzip()
    headers.containsBrotli -> BrotliInputStream(this.buffer().inputStream()).source()
    else -> this
}